/*
 * @(#)HolidayRecord.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.setup.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.dao.AbstractQuery;
import com.dcivision.framework.dao.QueryUtil;
import com.dcivision.framework.dao.SubQuery;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.setup.bean.HolidayRecord;
import com.dcivision.setup.web.ListHolidayRecordForm;

/**
 * HolidayRecordDAObject.java
 * 
 * This class is the data access bean for table "HOLIDAY_RECORD".
 * 
 * @author Weison Liang
 * @company DCIVision Limited
 * @creation date 13/04/2005
 * @version $Revision: 1.10 $
 */

public class HolidayRecordDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.10 $";

  public static final String TABLE_NAME = "HOLIDAY_RECORD";

  public HolidayRecordDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("WORKING_CALENDAR_ID");
    this.vecDBColumn.add("HOLIDAY_NAME");
    this.vecDBColumn.add("HOLIDAY_TYPE");
    this.vecDBColumn.add("START_DATE");
    this.vecDBColumn.add("END_DATE");
    this.vecDBColumn.add("DESCRIPTION");
    this.vecDBColumn.add("REFERENCE_FLAG");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   HOLIDAY_RECORD A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          HolidayRecord tmpHolidayRecord = getHolidayRecordByResultSet(rs); 
          return(tmpHolidayRecord);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    ListHolidayRecordForm actionForm=(ListHolidayRecordForm)searchForm;
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   HOLIDAY_RECORD A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ?  ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }
        if(!Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
          sqlStat.append("AND A.START_DATE >= ? AND A.END_DATE <= ? ");
        }else if(!Utility.isEmpty(actionForm.getStartDate()) && Utility.isEmpty(actionForm.getEndDate())){
          sqlStat.append("AND A.START_DATE >=? ");
        }else if(Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
          sqlStat.append("AND A.END_DATE <= ? ");
        }
        if(!Utility.isEmpty(actionForm.getHolidayType())){
          sqlStat.append("AND A.HOLIDAY_TYPE = ? ");
        }
        if(!Utility.isEmpty(actionForm.getRecord())){
          sqlStat.append("AND A.REFERENCE_FLAG = ? ");
        }
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
log.debug(sqlStat.toString());
        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int i = 1;
        this.setPrepareStatement(preStatCnt, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          this.setPrepareStatement(preStatCnt, i++, searchKeyword);
        }
        if(!Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
					this.setPrepareStatement(preStatCnt, i++, actionForm.getStartDate());
					this.setPrepareStatement(preStatCnt, i++, actionForm.getEndDate().substring(0,11)+"23:59:59" );
        }else if(!Utility.isEmpty(actionForm.getStartDate()) && Utility.isEmpty(actionForm.getEndDate())){
          this.setPrepareStatement(preStatCnt, i++, actionForm.getStartDate());
        }else if(Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
          this.setPrepareStatement(preStatCnt, i++, actionForm.getEndDate().substring(0,11)+"23:59:59" );
        }
        if(!Utility.isEmpty(actionForm.getHolidayType())){
          this.setPrepareStatement(preStatCnt, i++, actionForm.getHolidayType());
        }
        if(!Utility.isEmpty(actionForm.getRecord())){
          this.setPrepareStatement(preStatCnt, i++, actionForm.getRecord());
        }

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        i = 1;
        this.setPrepareStatement(preStat, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          this.setPrepareStatement(preStat, i++, searchKeyword);
        }
        if(!Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
					this.setPrepareStatement(preStat, i++, actionForm.getStartDate());
					this.setPrepareStatement(preStat, i++, actionForm.getEndDate().substring(0,11)+"23:59:59" );
        }else if(!Utility.isEmpty(actionForm.getStartDate()) && Utility.isEmpty(actionForm.getEndDate())){
          this.setPrepareStatement(preStat, i++, actionForm.getStartDate());
        }else if(Utility.isEmpty(actionForm.getStartDate()) && !Utility.isEmpty(actionForm.getEndDate())){
          this.setPrepareStatement(preStat, i++, actionForm.getEndDate().substring(0,11)+"23:59:59" );
        }
        if(!Utility.isEmpty(actionForm.getHolidayType())){
          this.setPrepareStatement(preStat, i++, actionForm.getHolidayType());
        }
        if(!Utility.isEmpty(actionForm.getRecord())){
          this.setPrepareStatement(preStat, i++, actionForm.getRecord());
        }

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);
        while (rs.next() && rowLoopCnt<pageSize) {
          HolidayRecord tmpHolidayRecord = getHolidayRecordByResultSet(rs); 
          tmpHolidayRecord.setRecordCount(totalNumOfRecord);
          tmpHolidayRecord.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpHolidayRecord);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    return this.getHolidayList(null,null,null,null,null,null);
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
log.debug("Validating insert object ...");
    HolidayRecord holidayRecord = (HolidayRecord)obj;
    List holidayList = getHolidayList (holidayRecord.getWorkingCalendarID(), 
        holidayRecord.getHolidayName(), holidayRecord.getHolidayType(), null, null, null 
      );
    if(!Utility.isEmpty(holidayList)){
      for(int i=0;i<holidayList.size();i++){
        HolidayRecord tmpRecord = (HolidayRecord)holidayList.get(i);
        if(Utility.isEmpty(holidayRecord.getID()) || (tmpRecord.getID().intValue() != holidayRecord.getID().intValue()) ){
          Calendar c1 = Utility.timestampToCalendar(tmpRecord.getStartDate());
          Calendar c2 = Utility.timestampToCalendar(holidayRecord.getStartDate());
          if(c1.get(Calendar.YEAR)==c2.get(Calendar.YEAR)){
            // If it's same holiday type with the same name and same year,
            // consider it as duplicated, note that for general holiday,
            // holiday will most probably be unique
            throw new ApplicationException (ErrorConstant.HOLIDAY_DUPLICATE_NAME, null, 
                new String[]{holidayRecord.getHolidayName()});
          }
        }
      }
    }
    List overlapList = getListOverlap (holidayRecord.getWorkingCalendarID(), 
        holidayRecord.getHolidayType(),
        TextUtility.getDBDateTimeFormat().format(holidayRecord.getStartDate()), 
        TextUtility.getDBDateTimeFormat().format(holidayRecord.getEndDate())
      );
    if(!Utility.isEmpty(overlapList)){
      for(int i=0;i<overlapList.size();i++){
        HolidayRecord tmpRecord = (HolidayRecord)overlapList.get(i);
      	if(Utility.isEmpty(holidayRecord.getID()) || tmpRecord.getID().intValue() != holidayRecord.getID().intValue()){
      	  throw new ApplicationException (ErrorConstant.HOLIDAY_OVERLAP_PERIOD, null, 
      	      new String[]{TextUtility.formatTimestampToDBDate(holidayRecord.getStartDate()), 
      	      TextUtility.formatTimestampToDBDate(holidayRecord.getEndDate())});
      	}
      }
    }
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
    validateInsert(obj);
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
log.debug("Validating delete object ...");
    HolidayRecord holidayRecord = (HolidayRecord)obj;
    if(HolidayRecord.REFERENCE_TYPE_REFERENCE.equals(holidayRecord.getReferenceFlag())){
log.warn("Deleting holiday reference "+holidayRecord.toString());      
    }
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    HolidayRecord tmpHolidayRecord = (HolidayRecord)((HolidayRecord)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   HOLIDAY_RECORD(ID, WORKING_CALENDAR_ID, HOLIDAY_NAME, HOLIDAY_TYPE, START_DATE, END_DATE, DESCRIPTION, REFERENCE_FLAG, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpHolidayRecord.getWorkingCalendarID());
        setPrepareStatement(preStat, 3, tmpHolidayRecord.getHolidayName());
        setPrepareStatement(preStat, 4, tmpHolidayRecord.getHolidayType());
        setPrepareStatement(preStat, 5, tmpHolidayRecord.getStartDate());
        setPrepareStatement(preStat, 6, tmpHolidayRecord.getEndDate());
        setPrepareStatement(preStat, 7, tmpHolidayRecord.getDescription());
        setPrepareStatement(preStat, 8, tmpHolidayRecord.getReferenceFlag());
        setPrepareStatement(preStat, 9, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 10, new Integer(0));
        setPrepareStatement(preStat, 11, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 12, currTime);
        setPrepareStatement(preStat, 13, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 14, currTime);
        preStat.executeUpdate();
        tmpHolidayRecord.setID(nextID);
        tmpHolidayRecord.setCreatorID(sessionContainer.getUserRecordID());
        tmpHolidayRecord.setCreateDate(currTime);
        tmpHolidayRecord.setUpdaterID(sessionContainer.getUserRecordID());
        tmpHolidayRecord.setUpdateDate(currTime);
        tmpHolidayRecord.setUpdateCount(new Integer(0));
        tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
        tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
        return(tmpHolidayRecord);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    HolidayRecord tmpHolidayRecord = (HolidayRecord)((HolidayRecord)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE HOLIDAY_RECORD ");
        sqlStat.append("SET  WORKING_CALENDAR_ID=?, HOLIDAY_NAME=?, HOLIDAY_TYPE=?, START_DATE=?, END_DATE=?, DESCRIPTION=?, REFERENCE_FLAG=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpHolidayRecord.getWorkingCalendarID());
        setPrepareStatement(preStat, 2, tmpHolidayRecord.getHolidayName());
        setPrepareStatement(preStat, 3, tmpHolidayRecord.getHolidayType());
        setPrepareStatement(preStat, 4, tmpHolidayRecord.getStartDate());
        setPrepareStatement(preStat, 5, tmpHolidayRecord.getEndDate());
        setPrepareStatement(preStat, 6, tmpHolidayRecord.getDescription());
        setPrepareStatement(preStat, 7, tmpHolidayRecord.getReferenceFlag());
        setPrepareStatement(preStat, 8, new Integer(tmpHolidayRecord.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 9, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 10, currTime);
        setPrepareStatement(preStat, 11, tmpHolidayRecord.getID());
        setPrepareStatement(preStat, 12, tmpHolidayRecord.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpHolidayRecord.setUpdaterID(sessionContainer.getUserRecordID());
          tmpHolidayRecord.setUpdateDate(currTime);
          tmpHolidayRecord.setUpdateCount(new Integer(tmpHolidayRecord.getUpdateCount().intValue() + 1));
          tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
          tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
          return(tmpHolidayRecord);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    HolidayRecord tmpHolidayRecord = (HolidayRecord)((HolidayRecord)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   HOLIDAY_RECORD ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpHolidayRecord.getID());
        setPrepareStatement(preStat, 2, tmpHolidayRecord.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpHolidayRecord);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    HolidayRecord tmpHolidayRecord = (HolidayRecord)this.oldValue;

    if (tmpHolidayRecord != null) {
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getID()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getWorkingCalendarID()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getHolidayName()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getHolidayType()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getStartDate()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getEndDate()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getDescription()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getReferenceFlag()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdateDate()));
    }

    tmpHolidayRecord = (HolidayRecord)obj;
    if (tmpHolidayRecord != null) {
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getID()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getWorkingCalendarID()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getHolidayName()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getHolidayType()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getStartDate()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getEndDate()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getDescription()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getReferenceFlag()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpHolidayRecord.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/

  public List getHolidayNameListByCalendarIDdate(Integer workingCalendarID) throws ApplicationException {
    return getHolidayList(workingCalendarID, null, null, null, null, null);
  }

  public List getListByCalendarID(Integer workingCalendarID) throws ApplicationException {
    return getHolidayList(workingCalendarID, null, null, null, null, null);
  }

  public List getListByHolidayTypeRefence(String referenceFlag) throws ApplicationException {
    return getHolidayList(null, null, null, referenceFlag, null, null);
  }

  public List getHolidayNameListBydate(Integer workingCalendarID, String startDate, String endDate) throws ApplicationException {
    return getHolidayList(workingCalendarID, null, null, null, startDate, endDate);
  }

  public List getHolidayList(Integer workingCalendarID, String holidayName, Integer holidayType, String referenceFlag, String startDate, String endDate) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    try {
      sqlStat.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
      sqlStat.append("FROM   HOLIDAY_RECORD A ");
      sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
      if(!Utility.isEmpty(workingCalendarID)){
        sqlStat.append("  AND  A.WORKING_CALENDAR_ID = ? ");
      }
      if(!Utility.isEmpty(holidayName)){
        sqlStat.append("  AND  A.HOLIDAY_NAME = ? ");
      }
      if(!Utility.isEmpty(holidayType)){
        sqlStat.append("  AND  A.HOLIDAY_TYPE = ? ");
      }
      if(!Utility.isEmpty(referenceFlag)){
        sqlStat.append("  AND  A.REFERENCE_FLAG = ? ");
      }
      if(!Utility.isEmpty(startDate)&&!Utility.isEmpty(endDate)){
        sqlStat.append("  AND  A.START_DATE >= ? AND A.END_DATE <= ? ");
      }
      
      preStat = dbConn.prepareStatement(sqlStat.toString());
      int i=1;
      this.setPrepareStatement(preStat, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      if(!Utility.isEmpty(workingCalendarID)){
        this.setPrepareStatement(preStat, i++, workingCalendarID);
      }
      if(!Utility.isEmpty(holidayName)){
        this.setPrepareStatement(preStat, i++, holidayName);
      }
      if(!Utility.isEmpty(holidayType)){
        this.setPrepareStatement(preStat, i++, holidayType);
      }
      if(!Utility.isEmpty(referenceFlag)){
        this.setPrepareStatement(preStat, i++, referenceFlag);
      }
      if(!Utility.isEmpty(startDate)&&!Utility.isEmpty(endDate)){
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
      }
      rs = preStat.executeQuery();
      while (rs.next()) {
        HolidayRecord tmpHolidayRecord = getHolidayRecordByResultSet(rs); 
        result.add(tmpHolidayRecord);
      }
      return(result);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
    }
  }
  
  private HolidayRecord getHolidayRecordByResultSet(ResultSet rs) throws Exception {
    HolidayRecord tmpHolidayRecord = new HolidayRecord();
    try {
      tmpHolidayRecord.setID(getResultSetInteger(rs, "ID"));
      tmpHolidayRecord.setWorkingCalendarID(getResultSetInteger(rs, "WORKING_CALENDAR_ID"));
      tmpHolidayRecord.setHolidayName(getResultSetString(rs, "HOLIDAY_NAME"));
      tmpHolidayRecord.setHolidayType(getResultSetInteger(rs, "HOLIDAY_TYPE"));
      tmpHolidayRecord.setStartDate(getResultSetTimestamp(rs, "START_DATE"));
      tmpHolidayRecord.setEndDate(getResultSetTimestamp(rs, "END_DATE"));
      tmpHolidayRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
      tmpHolidayRecord.setReferenceFlag(getResultSetString(rs, "REFERENCE_FLAG"));
      tmpHolidayRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
      tmpHolidayRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
      tmpHolidayRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
      tmpHolidayRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
      tmpHolidayRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
      tmpHolidayRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
      tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
      tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
      return tmpHolidayRecord;
    } catch (Exception e) {
      throw e;
    }
  }
  
  public List getListOverlap ( Integer workingCalendarID, Integer holidayType, String startDate, String endDate ) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    try {
      sqlStat.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
      sqlStat.append("FROM   HOLIDAY_RECORD A ");
      sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
      if(!Utility.isEmpty(workingCalendarID)){
        sqlStat.append("  AND  A.WORKING_CALENDAR_ID = ? ");
      }
      if(!Utility.isEmpty(holidayType)){
        sqlStat.append("  AND  A.HOLIDAY_TYPE = ? ");
      }
      if(!Utility.isEmpty(startDate)&&!Utility.isEmpty(endDate)){
        sqlStat.append("  AND (   (A.START_DATE >= ? AND A.START_DATE <= ?) ");
        sqlStat.append("        OR(A.END_DATE >= ? AND A.END_DATE <= ?) ");
      	sqlStat.append("        OR(A.START_DATE < ? AND A.END_DATE > ?) ) ");
      }
    
      preStat = dbConn.prepareStatement(sqlStat.toString());
      int i=1;
      this.setPrepareStatement(preStat, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      if(!Utility.isEmpty(workingCalendarID)){
        this.setPrepareStatement(preStat, i++, workingCalendarID);
      }
      if(!Utility.isEmpty(holidayType)){
        this.setPrepareStatement(preStat, i++, holidayType);
      }
      if(!Utility.isEmpty(startDate)&&!Utility.isEmpty(endDate)){
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
      }
      rs = preStat.executeQuery();
      while (rs.next()) {
        HolidayRecord tmpHolidayRecord = getHolidayRecordByResultSet(rs); 
        result.add(tmpHolidayRecord);
      }
      return(result);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
    }
  }
  
  /**
   * get holiday record list by working calendar ID, start date and end date.
   * @param workingCalendarID
   * @param startDate
   * @param endDate
   * @return
   * @throws ApplicationException
   */

  public List getHolidayRecordListByWorkingCalendarIDStartDateEndDate(
        Integer workingCalendarID, String startDate,String endDate ) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    try {
      sqlStat.append(" SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
      sqlStat.append(" FROM   HOLIDAY_RECORD A ");
      sqlStat.append(" WHERE  A.WORKING_CALENDAR_ID = ? AND A.RECORD_STATUS = ? ");
      sqlStat.append(" AND (");
      if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        sqlStat.append("  ( A.START_DATE >= to_date(? , 'YYYY-MM-DD HH24:MI:SS') ");
        sqlStat.append("  AND A.END_DATE <= to_date(? , 'YYYY-MM-DD HH24:MI:SS') ) ");
        sqlStat.append(" OR ");
        sqlStat.append("  (A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') ");
        sqlStat.append("  AND A.END_DATE > to_date(? , 'YYYY-MM-DD HH24:MI:SS') ) ");
      } else {
        sqlStat.append("  ( A.START_DATE >= ? ");
        sqlStat.append("  AND A.END_DATE <= ? )");
        sqlStat.append(" OR ");
        sqlStat.append("  ( A.START_DATE < ? ");
        sqlStat.append("  AND A.END_DATE > ? )");
      }
      sqlStat.append(" ) ");
      sqlStat.append(" AND A.HOLIDAY_TYPE = ? ");
      sqlStat.append(" ORDER BY A.START_DATE ");

      preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      this.setPrepareStatement(preStat, 1, workingCalendarID);
      this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
      this.setPrepareStatement(preStat, 3, TextUtility.parseDBDateTimeToTimeStamp(startDate));
      this.setPrepareStatement(preStat, 4, TextUtility.parseDBDateTimeToTimeStamp(endDate));
      this.setPrepareStatement(preStat, 5, TextUtility.parseDBDateTimeToTimeStamp(endDate));
      this.setPrepareStatement(preStat, 6, TextUtility.parseDBDateTimeToTimeStamp(endDate));
      this.setPrepareStatement(preStat, 7, HolidayRecord.REFERENCE_TYPE_RECORD);
      rs = preStat.executeQuery();
      while (rs.next()) {
        HolidayRecord tmpHolidayRecord = new HolidayRecord();
        tmpHolidayRecord.setID(getResultSetInteger(rs, "ID"));
        tmpHolidayRecord.setWorkingCalendarID(getResultSetInteger(rs, "WORKING_CALENDAR_ID"));
        tmpHolidayRecord.setHolidayName(getResultSetString(rs, "HOLIDAY_NAME"));
        tmpHolidayRecord.setHolidayType(getResultSetInteger(rs, "HOLIDAY_TYPE"));
        tmpHolidayRecord.setStartDate(getResultSetTimestamp(rs, "START_DATE"));
        tmpHolidayRecord.setEndDate(getResultSetTimestamp(rs, "END_DATE"));
        tmpHolidayRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
        tmpHolidayRecord.setReferenceFlag(getResultSetString(rs, "REFERENCE_FLAG"));
        tmpHolidayRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
        tmpHolidayRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
        tmpHolidayRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
        tmpHolidayRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
        tmpHolidayRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
        tmpHolidayRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
        tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
        tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
        result.add(tmpHolidayRecord);
      }
      return(result);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
    }
  }
  
  public List getDistinctHolidayRecordListByWorkingCalendarIDAndDatePoint(
      Integer workingCalendarID, String startDate, String endDate) throws ApplicationException {
    AbstractQuery query = QueryUtil.createQuery();
    AbstractQuery publicHolidayListSubQuery = this.getPublicHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
        workingCalendarID, startDate, endDate);
    AbstractQuery generalHolidayListSubQuery = this.getGeneralHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
        workingCalendarID, startDate, endDate);
    query.subQuery(publicHolidayListSubQuery);
    query.append("\n UNION \n");
    query.subQuery(generalHolidayListSubQuery);
    query.pack();
    
    ArrayList result = new ArrayList();
    PreparedStatement preStat = null;
    ResultSet rs = null;
    synchronized(dbConn) {
      try {
        preStat = this.dbConn.prepareStatement(query.toString());
        log.info("query: " + query.toString());
        this.setPreparedStatement(preStat, 1, query.getAllParameters());
        rs = preStat.executeQuery();
        while (rs.next()) {
          HolidayRecord tmpHolidayRecord = new HolidayRecord();
          tmpHolidayRecord.setID(getResultSetInteger(rs, "ID"));
          tmpHolidayRecord.setWorkingCalendarID(getResultSetInteger(rs, "WORKING_CALENDAR_ID"));
          tmpHolidayRecord.setHolidayName(getResultSetString(rs, "HOLIDAY_NAME"));
          tmpHolidayRecord.setHolidayType(getResultSetInteger(rs, "HOLIDAY_TYPE"));
          tmpHolidayRecord.setStartDate(getResultSetTimestamp(rs, "START_DATE"));
          tmpHolidayRecord.setEndDate(getResultSetTimestamp(rs, "END_DATE"));
          tmpHolidayRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpHolidayRecord.setReferenceFlag(getResultSetString(rs, "REFERENCE_FLAG"));
          tmpHolidayRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpHolidayRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpHolidayRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpHolidayRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpHolidayRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpHolidayRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
          tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
          result.add(tmpHolidayRecord);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  protected AbstractQuery getPublicHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
      Integer workingCalendarID, String startDate, String endDate) throws ApplicationException {
    AbstractQuery subQuery = new SubQuery();
    StringBuffer sqlStat = new StringBuffer();
    sqlStat.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE \n");
    sqlStat.append("FROM HOLIDAY_RECORD A \n");
    sqlStat.append("WHERE A.WORKING_CALENDAR_ID = ? \n");
    sqlStat.append("  AND A.RECORD_STATUS = ? \n");
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      sqlStat.append("  AND ((A.START_DATE >= to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE <= ?) \n");
      sqlStat.append("  OR (A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE > ?)) \n");
    } else {
      sqlStat.append("  AND ((A.START_DATE >= ? AND A.END_DATE <= ?) \n");
      sqlStat.append("  OR (A.START_DATE < ? AND A.END_DATE > ?)) \n");
    }
    sqlStat.append("  AND A.HOLIDAY_TYPE = ?");
    subQuery.append(sqlStat.toString());
    int i = 1;
    subQuery.setParameter(i++, workingCalendarID);
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, HolidayRecord.HOLIDAY_TYPE_PUBLIC);
    subQuery.pack();
    return (subQuery);
  }
  
  protected AbstractQuery getGeneralHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
      Integer workingCalendarID, String startDate, String endDate) throws ApplicationException {
    AbstractQuery subQuery = new SubQuery();
    AbstractQuery generalInPublicHolidayListSubQuery = this.getGeneralInPublicHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
        workingCalendarID, startDate, endDate);
    
    subQuery.append("SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE \n");
    subQuery.append("FROM HOLIDAY_RECORD A \n");
    subQuery.append("WHERE A.WORKING_CALENDAR_ID = ? \n");
    subQuery.append("  AND A.RECORD_STATUS = ? \n");
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      subQuery.append("  AND ((A.START_DATE >= to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE <= ?) \n");
      subQuery.append("  OR (A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE > ?)) \n");
    } else {
      subQuery.append("  AND ((A.START_DATE >= ? AND A.END_DATE <= ?) \n");
      subQuery.append("  OR (A.START_DATE < ? AND A.END_DATE > ?)) \n");
    }
    subQuery.append("  AND A.HOLIDAY_TYPE = ? \n");
    subQuery.append("  AND A.ID NOT IN (").subQuery(generalInPublicHolidayListSubQuery).append(")");
    int i = 1;
    subQuery.setParameter(i++, workingCalendarID);
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, HolidayRecord.HOLIDAY_TYPE_GENERAL);
    subQuery.pack();
    return (subQuery);
  }
  
  protected AbstractQuery getGeneralInPublicHolidayRecordListQueryByWorkingCalendarIDAndDatePoint(
      Integer workingCalendarID, String startDate, String endDate) throws ApplicationException {
    AbstractQuery subQuery = new SubQuery();
    StringBuffer sqlStat = new StringBuffer();
    sqlStat.append("SELECT A.ID \n");
    sqlStat.append("FROM HOLIDAY_RECORD A JOIN HOLIDAY_RECORD B \n");
    sqlStat.append("WHERE A.WORKING_CALENDAR_ID = ? \n");
    sqlStat.append("  AND A.RECORD_STATUS = ? \n");
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      sqlStat.append("  AND ((A.START_DATE >= to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE <= ?) \n");
      sqlStat.append("  OR (A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND A.END_DATE > ?)) \n");
    } else {
      sqlStat.append("  AND ((A.START_DATE >= ? AND A.END_DATE <= ?) \n");
      sqlStat.append("  OR (A.START_DATE < ? AND A.END_DATE > ?)) \n");
    }
    sqlStat.append("  AND A.HOLIDAY_TYPE = ? \n");
    sqlStat.append("  AND B.WORKING_CALENDAR_ID = ? \n");
    sqlStat.append("  AND B.RECORD_STATUS = ? \n");
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      sqlStat.append("  AND ((B.START_DATE >= to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND B.END_DATE <= ?) \n");
      sqlStat.append("  OR (B.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') AND B.END_DATE > ?)) \n");
    } else {
      sqlStat.append("  AND ((B.START_DATE >= ? AND B.END_DATE <= ?) \n");
      sqlStat.append("  OR (B.START_DATE < ? AND B.END_DATE > ?)) \n");
    }
    sqlStat.append("  AND B.HOLIDAY_TYPE = ? \n");
    sqlStat.append("  AND A.START_DATE >= B.START_DATE \n");
    sqlStat.append("  AND A.END_DATE <= B.END_DATE \n");
    
    subQuery.append(sqlStat.toString());
    int i = 1;
    subQuery.setParameter(i++, workingCalendarID);
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, HolidayRecord.HOLIDAY_TYPE_GENERAL);
    subQuery.setParameter(i++, workingCalendarID);
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(startDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, TextUtility.parseDBDateTimeToTimeStamp(endDate));
    subQuery.setParameter(i++, HolidayRecord.HOLIDAY_TYPE_PUBLIC);
    subQuery.pack();
    return (subQuery);
  }
  
  /**
   * Get the lateat holiday record include the given date point.
   */
  public AbstractBaseObject getLatestHolidayRecordByWorkingCalendarIDAndDatePoint(
      Integer workingCalendarID, String datePoint) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized(dbConn) {   
      try {
        sqlStat.append("SELECT MAX(A.END_DATE) END_DATE, A.ID, A.WORKING_CALENDAR_ID," +
            "A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.DESCRIPTION," +
            "A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE," +
            "A.UPDATER_ID, A.UPDATE_DATE \n");
        sqlStat.append("FROM HOLIDAY_RECORD A \n");
        sqlStat.append("WHERE  A.WORKING_CALENDAR_ID = ? AND A.RECORD_STATUS = ? \n");
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
          sqlStat.append("  AND A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') \n");
          sqlStat.append("  AND A.END_DATE > to_date(? , 'YYYY-MM-DD HH24:MI:SS') \n");
        } else {
          sqlStat.append("  AND A.START_DATE < ? \n");
          sqlStat.append("  AND A.END_DATE > ? \n");
        }
        sqlStat.append("  AND (A.HOLIDAY_TYPE = ? \n");
        sqlStat.append("  OR A.HOLIDAY_TYPE = ?) \n");
        sqlStat.append("  GROUP BY A.WORKING_CALENDAR_ID");
        
        preStat = this.dbConn.prepareStatement(sqlStat.toString());
        int i = 1;
        this.setPrepareStatement(preStat, i++, workingCalendarID);
        this.setPrepareStatement(preStat, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(datePoint));
        this.setPrepareStatement(preStat, i++, TextUtility.parseDBDateTimeToTimeStamp(datePoint));
        this.setPrepareStatement(preStat, i++, HolidayRecord.HOLIDAY_TYPE_GENERAL);
        this.setPrepareStatement(preStat, i++, HolidayRecord.HOLIDAY_TYPE_PUBLIC);
        
        rs = preStat.executeQuery();
        if (rs.next()) {
          HolidayRecord tmpHolidayRecord = new HolidayRecord();
          tmpHolidayRecord.setID(getResultSetInteger(rs, "ID"));
          tmpHolidayRecord.setWorkingCalendarID(getResultSetInteger(rs, "WORKING_CALENDAR_ID"));
          tmpHolidayRecord.setHolidayName(getResultSetString(rs, "HOLIDAY_NAME"));
          tmpHolidayRecord.setHolidayType(getResultSetInteger(rs, "HOLIDAY_TYPE"));
          tmpHolidayRecord.setStartDate(getResultSetTimestamp(rs, "START_DATE"));
          tmpHolidayRecord.setEndDate(getResultSetTimestamp(rs, "END_DATE"));
          tmpHolidayRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpHolidayRecord.setReferenceFlag(getResultSetString(rs, "REFERENCE_FLAG"));
          tmpHolidayRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpHolidayRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpHolidayRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpHolidayRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpHolidayRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpHolidayRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
          tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
          return (tmpHolidayRecord);
        }
        return null;
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * get holiday record object by working calendar ID and date point
   * @param workingCalendarID
   * @param datePoint
   * @return
   * @throws ApplicationException
   */

  public AbstractBaseObject getHolidayRecordObjectByWorkingCalendarIDDatePoint(
      Integer workingCalendarID, String datePoint ) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    try {
      sqlStat.append(" SELECT A.ID, A.WORKING_CALENDAR_ID, A.HOLIDAY_NAME, A.HOLIDAY_TYPE, A.START_DATE, A.END_DATE, A.DESCRIPTION, A.REFERENCE_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
      sqlStat.append(" FROM   HOLIDAY_RECORD A ");
      sqlStat.append(" WHERE  A.WORKING_CALENDAR_ID = ? AND A.RECORD_STATUS = ? ");

      if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        sqlStat.append("  AND A.START_DATE < to_date(? , 'YYYY-MM-DD HH24:MI:SS') \n");
        sqlStat.append("  AND A.END_DATE > to_date(? , 'YYYY-MM-DD HH24:MI:SS') \n");
      } else {
        sqlStat.append("  AND A.START_DATE < ? \n");
        sqlStat.append("  AND A.END_DATE > ? \n");
      }

      sqlStat.append(" AND A.HOLIDAY_TYPE = ? ");
      sqlStat.append(" ORDER BY A.START_DATE ");

      preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      this.setPrepareStatement(preStat, 1, workingCalendarID);
      this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
      this.setPrepareStatement(preStat, 3, TextUtility.parseDBDateTimeToTimeStamp(datePoint));
      this.setPrepareStatement(preStat, 4, TextUtility.parseDBDateTimeToTimeStamp(datePoint));
      this.setPrepareStatement(preStat, 5, HolidayRecord.REFERENCE_TYPE_RECORD);
      rs = preStat.executeQuery();
      if (rs.next()) {
        HolidayRecord tmpHolidayRecord = new HolidayRecord();
        tmpHolidayRecord.setID(getResultSetInteger(rs, "ID"));
        tmpHolidayRecord.setWorkingCalendarID(getResultSetInteger(rs, "WORKING_CALENDAR_ID"));
        tmpHolidayRecord.setHolidayName(getResultSetString(rs, "HOLIDAY_NAME"));
        tmpHolidayRecord.setHolidayType(getResultSetInteger(rs, "HOLIDAY_TYPE"));
        tmpHolidayRecord.setStartDate(getResultSetTimestamp(rs, "START_DATE"));
        tmpHolidayRecord.setEndDate(getResultSetTimestamp(rs, "END_DATE"));
        tmpHolidayRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
        tmpHolidayRecord.setReferenceFlag(getResultSetString(rs, "REFERENCE_FLAG"));
        tmpHolidayRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
        tmpHolidayRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
        tmpHolidayRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
        tmpHolidayRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
        tmpHolidayRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
        tmpHolidayRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
        tmpHolidayRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getCreatorID()));
        tmpHolidayRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpHolidayRecord.getUpdaterID()));
        //result.add(tmpHolidayRecord);
        return tmpHolidayRecord;
      }
      return null;
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
    }
  }

}
